//package com.yunxin.core.application.service.impl;
//
//import com.yunxin.common.utils.SnowflakeKeyGenerator;
//import com.yunxin.core.application.assembler.ChannelAssembler;
//import com.yunxin.core.application.command.channel.ChannelCustomerApplyCommand;
//import com.yunxin.core.application.command.channel.ChannelCustomerApplyLibraryCommand;
//import com.yunxin.core.application.dto.channel.ChannelCustomerApplyDTO;
//import com.yunxin.core.application.dto.user.UserJointLoginDTO;
//import com.yunxin.core.application.service.ChannelApplicationOpenapiService;
//import com.yunxin.core.application.service.UserApplicationOpenapiService;
//import com.yunxin.core.domain.external.channel.ChannelExternalService;
//import com.yunxin.core.domain.external.channel.ChannelPromotionPriceInfo;
//import com.yunxin.core.domain.external.product.ProductExternalService;
//import com.yunxin.core.domain.external.product.ProductThrowInDetail;
//import com.yunxin.core.domain.model.channel.ChannelCustomerApplyLibraryRecord;
//import com.yunxin.core.domain.model.channel.ChannelCustomerApplyLibraryRecordRepository;
//import com.yunxin.core.domain.model.channel.ChannelPromotionApiCustomerConfig;
//import com.yunxin.core.domain.model.channel.ChannelPromotionApiCustomerConfigRepository;
//import com.yunxin.core.domain.model.order.AllocationOrderUserApplyResult;
//import com.yunxin.core.domain.model.order.OrderUserApply;
//import com.yunxin.core.domain.model.order.OrderUserApplyDetail;
//import com.yunxin.core.domain.model.user.UserAuth;
//import com.yunxin.core.domain.model.user.UserAuthRepository;
//import com.yunxin.core.domain.model.user.UserInfo;
//import com.yunxin.core.domain.service.order.OrderService;
//import com.yunxin.core.domain.service.order.impl.OrderUserApplyAllocationHandle;
//import com.yunxin.core.infra.common.channel.utils.ChannelCustomerAttributeDetermineUtils;
//import com.yunxin.core.infra.persistence.entity.channel.ChannelPromotionDO;
//import com.yunxin.core.infra.persistence.mapper.channel.ChannelPromotionExtendMapper;
//import com.yunxin.core.infra.persistence.repository.user.UserInfoRepositoryImpl;
//import com.yunxin.core.utils.infra.common.enums.KeyGeneratorPrefixEnum;
//import lombok.RequiredArgsConstructor;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Service;
//
//import java.util.Objects;
//
///**
// * @author zero°
// * @since 2023-12-14
// */
//@Slf4j
//@Service
//@RequiredArgsConstructor
//public class ChannelApplicationOpenapiServiceImpl implements ChannelApplicationOpenapiService {
//
//    private final ChannelAssembler channelAssembler;
//
//    private final ChannelPromotionExtendMapper channelPromotionExtendMapper;
//
//    private final ChannelPromotionApiCustomerConfigRepository channelPromotionApiCustomerConfigRepository;
//
//    private final ChannelCustomerApplyLibraryRecordRepository channelCustomerApplyLibraryRecordRepository;
//
//    private final UserApplicationOpenapiService userApplicationOpenapiService;
//
//    private final OrderUserApplyAllocationHandle orderUserApplyAllocationHandle;
//
//    private final ChannelExternalService channelExternalService;
//
//    private final ProductExternalService productExternalService;
//
//    private final OrderService orderService;
//
//    private final SnowflakeKeyGenerator sequenceGenerator;
//
//    private final UserAuthRepository userAuthRepository;
//
//    private final UserInfoRepositoryImpl userInfoRepository;
//
//    /**
//     * 订单撞库，保存用户撞库记录
//     *
//     * @param channelCustomerApplyLibraryCommand channelCustomerApplyLibraryCommand
//     * @return
//     */
//    @Override
//    public String customerApplyLibrary(ChannelCustomerApplyLibraryCommand channelCustomerApplyLibraryCommand) {
//        //查询改MD5在数据库是否存在
//        String md5Phone = channelCustomerApplyLibraryCommand.getMd5Phone();
//        String channelPromotionCode = channelCustomerApplyLibraryCommand.getChannelPromotionCode();
//        UserInfo userInfo = userInfoRepository.getUserInfoByMd5Phone(md5Phone);
//        if (null != userInfo) {
//            log.info("渠道撞库失败!promotionCode={},该手机号已存在！MD5phone={}", channelCustomerApplyLibraryCommand.getChannelPromotionCode(), userInfo.getMd5Phone());
//            return null;
//        }
//        //根据渠道code查询该渠道状态
//        ChannelPromotionDO channelPromotionDO = channelPromotionExtendMapper.getStatusByCode(channelPromotionCode);
//        if (channelPromotionDO.getPromotionStatus() == 1) {
//            if (!("cyr").equals(channelPromotionCode)){
//                log.info("渠道撞库失败!promotionCode={},当前渠道状态已关闭！status = {},MD5phone={}", channelPromotionCode, channelPromotionDO.getPromotionStatus(), md5Phone);
//            }
//            return null;
//        }
//        ChannelPromotionApiCustomerConfig channelPromotionApiCustomerConfig = channelPromotionApiCustomerConfigRepository.getChannelPromotionApiCustomerConfigByPromotionCode(channelPromotionCode);
//        if (Objects.isNull(channelPromotionApiCustomerConfig)) {
//            log.info("渠道撞库失败!promotionCode={} 渠道api客户配置不存在, ", channelPromotionCode);
//            log.info("data={}", channelCustomerApplyLibraryCommand);
//            return null;
//        }
//        boolean result = ChannelCustomerAttributeDetermineUtils.X.isMatchResult(channelCustomerApplyLibraryCommand, channelPromotionApiCustomerConfig);
//        if (!result) {
//            log.info("渠道撞库失败!promotionCode={}, 渠道客户配置不匹配,  md5Phone={}", channelPromotionCode, md5Phone);
//            log.info("data={}", channelCustomerApplyLibraryCommand);
//            return null;
//        }
//        ChannelCustomerApplyLibraryRecord channelCustomerApplyLibraryRecord = channelAssembler.fromChannelCustomerApplyLibraryRecord(channelCustomerApplyLibraryCommand);
//        //生产密钥
//        String libraryNo = sequenceGenerator.generateKey(KeyGeneratorPrefixEnum.LIBRARY_ORDER.getPrefix());
//        channelCustomerApplyLibraryRecord.setLibraryNo(libraryNo);
//        //保存渠道客户申请记录
//        boolean saveResult = channelCustomerApplyLibraryRecordRepository.saveChannelCustomerApplyLibraryRecord(channelCustomerApplyLibraryRecord);
//        log.info("渠道撞库{}!promotionCode={}", saveResult, channelPromotionCode);
//        return saveResult ? libraryNo : null;
//    }
//
//
//    /**
//     * 客户申请进件
//     *
//     * @param channelCustomerApplyCommand channelCustomerApplyCommand
//     * @return
//     */
//    @Override
//    public ChannelCustomerApplyDTO customerApply(ChannelCustomerApplyCommand channelCustomerApplyCommand) {
//        ChannelCustomerApplyDTO channelCustomerApplyDTO = new ChannelCustomerApplyDTO();
//        channelCustomerApplyDTO.setStatus(Boolean.TRUE);
//        //根据唯一标识查询渠道客户撞库记录
//        ChannelCustomerApplyLibraryRecord channelCustomerApplyLibraryRecord = channelCustomerApplyLibraryRecordRepository.getChannelCustomerApplyLibraryRecordByLibraryNo(channelCustomerApplyCommand.getCid());
//        if (Objects.isNull(channelCustomerApplyLibraryRecord)) {
//            log.info("渠道进件失败!promotionCode={}, 唯一标识记录不存在,  cid={}", channelCustomerApplyCommand.getChannelPromotionCode(), channelCustomerApplyCommand.getCid());
//            channelCustomerApplyDTO.setStatus(Boolean.FALSE);
//            return channelCustomerApplyDTO;
//        }
//        // 用户联登
//        UserJointLoginDTO userJointLoginDTO = userApplicationOpenapiService.jointLogin(channelCustomerApplyCommand.getPhone(), channelCustomerApplyCommand.getChannelPromotionCode(),
//                channelCustomerApplyCommand.getClientIp(), channelCustomerApplyCommand.getCity(), null);
//        if (Boolean.FALSE.equals(userJointLoginDTO.getIsNewUser())) {
//            log.info("渠道进件失败!promotionCode={}, 手机号用户已存在,  phone={}", channelCustomerApplyCommand.getChannelPromotionCode(), channelCustomerApplyCommand.getPhone());
//            log.info("data={}", channelCustomerApplyCommand);
//            channelCustomerApplyDTO.setStatus(Boolean.FALSE);
//            return channelCustomerApplyDTO;
//        }
//        //根据手机号查询用户申请订单
//        ChannelPromotionPriceInfo channelPromotionPriceInfo = channelExternalService.getChannelPromotionPriceInfoByPromotionCode(channelCustomerApplyCommand.getChannelPromotionCode());
//        if (Objects.isNull(channelPromotionPriceInfo)) {
//            log.info("渠道进件失败!promotionCode={}, 渠道不存在, channelPromotionCode={}", channelCustomerApplyCommand.getChannelPromotionCode(), channelCustomerApplyCommand.getChannelPromotionCode());
//            log.info("data={}", channelCustomerApplyCommand);
//            channelCustomerApplyDTO.setStatus(Boolean.FALSE);
//            return channelCustomerApplyDTO;
//        }
//        channelCustomerApplyDTO.setUserJointLoginDTO(userJointLoginDTO);
//        // 保存用户采集单
//        String applyOrderNo = createUserApplyOrder(channelCustomerApplyCommand, channelPromotionPriceInfo, userJointLoginDTO.getUserCode());
//        channelCustomerApplyDTO.setOrderNo(applyOrderNo);
//        // 分配订单 这里不能catch异常,PushOrderAction原本有异常会给上游返回进件失败
//        AllocationOrderUserApplyResult allocationOrderUserApplyResult = orderUserApplyAllocationHandle.allocationOrderUserApply(applyOrderNo, channelCustomerApplyCommand.getClientIp());
//        channelCustomerApplyDTO.setProductId(allocationOrderUserApplyResult.getProductId());
//        ProductThrowInDetail productThrowInDetail = productExternalService.selectProductThrowInDetailByProductId(allocationOrderUserApplyResult.getProductId());
//        channelCustomerApplyDTO.setJumpUrl(productThrowInDetail.getJumpUrl());
//        log.info("渠道进件{}!promotionCode={}", channelCustomerApplyCommand.getChannelPromotionCode());
//        return channelCustomerApplyDTO;
//    }
//
//    /**
//     * 创建用户采集但
//     *
//     * @param channelCustomerApplyCommand channelCustomerApplyCommand
//     * @param channelPromotionPriceInfo   channelPromotionPriceInfo
//     * @param userCode                    userCode
//     * @return String
//     */
//    private String createUserApplyOrder(ChannelCustomerApplyCommand channelCustomerApplyCommand, ChannelPromotionPriceInfo channelPromotionPriceInfo, String userCode) {
//        OrderUserApply orderUserApply = new OrderUserApply();
//        orderUserApply.setUserCode(userCode);
//        UserAuth userAuth = userAuthRepository.getVisitorIdByUserCode(userCode);
//        orderUserApply.setVisitorId(userAuth.getIdentifierMd5());
//
//        if (null != channelCustomerApplyCommand.getName())
//            orderUserApply.setUserName(channelCustomerApplyCommand.getName());
//        orderUserApply.setUserPhone(channelCustomerApplyCommand.getPhone());
//        orderUserApply.setCity(channelCustomerApplyCommand.getCity());
//        //生产用户申请订单号
//        orderUserApply.setApplyOrderNo(sequenceGenerator.generateKey(KeyGeneratorPrefixEnum.ORDER.getPrefix()));
//        orderUserApply.setChannelPromotionPrice(channelPromotionPriceInfo.getChannelPromotionPrice());
//        orderUserApply.setChannelPromotionPriceVersion(channelPromotionPriceInfo.getChannelPromotionPriceVersion());
//
//        // OrderUserApplyDetail orderUserApplyDetail = new OrderUserApplyDetail();
//
//        //渠道推广code，渠道id，分配状态
//        orderUserApply.setChannelPromotionCode(channelCustomerApplyCommand.getChannelPromotionCode());
//        orderUserApply.setChannelId(channelPromotionPriceInfo.getChannelId());
//        orderUserApply.setAllocationStatus(0);
//
//        //转换订单详情
//        OrderUserApplyDetail orderUserApplyDetail = convertOrderUserApplyDetail(channelCustomerApplyCommand);
//        orderUserApplyDetail.setApplyOrderNo(orderUserApply.getApplyOrderNo());
//        //保存用户申请订单和用户申请订单明细订单
//        orderService.saveOrderUserApply(orderUserApply, orderUserApplyDetail);
//        //返回申请订单号
//        return orderUserApply.getApplyOrderNo();
//    }
//
//    /**
//     * 转换订单详情
//     *
//     * @param channelCustomerApplyCommand channelCustomerApplyCommand
//     */
//    private OrderUserApplyDetail convertOrderUserApplyDetail(ChannelCustomerApplyCommand channelCustomerApplyCommand) {
//        OrderUserApplyDetail orderUserApplyDetail = new OrderUserApplyDetail();
//        //城市
//        orderUserApplyDetail.setWorkCity(channelCustomerApplyCommand.getCity());
//        orderUserApplyDetail.setEducationLevel(channelCustomerApplyCommand.getEducationLevel());
//        orderUserApplyDetail.setBeOverdue(channelCustomerApplyCommand.getBeOverdue());
//        orderUserApplyDetail.setSocialSecurityLevel(channelCustomerApplyCommand.getSocialSecurityLevel());
//        orderUserApplyDetail.setAccumulationFundLevel(channelCustomerApplyCommand.getAccumulationFundLevel());
//        orderUserApplyDetail.setMicroLoanQuota(channelCustomerApplyCommand.getMicroLoanQuota());
//        orderUserApplyDetail.setSesameSeedQuota(channelCustomerApplyCommand.getSesameSeedQuota());
//        orderUserApplyDetail.setCreditCard(channelCustomerApplyCommand.getCreditCard());
//        orderUserApplyDetail.setOccupation(channelCustomerApplyCommand.getOccupation());
//        orderUserApplyDetail.setOccupationMonthlyIncome(channelCustomerApplyCommand.getOccupationMonthlyIncome());
//        orderUserApplyDetail.setHouseLevel(channelCustomerApplyCommand.getHouseLevel());
//        orderUserApplyDetail.setVehicleLevel(channelCustomerApplyCommand.getVehicleLevel());
//        orderUserApplyDetail.setInsure(channelCustomerApplyCommand.getInsure());
//        if (null != channelCustomerApplyCommand.getLoanAmount())
//            orderUserApplyDetail.setLoanAmount(channelCustomerApplyCommand.getLoanAmount());
//        if (null != channelCustomerApplyCommand.getLoanPeriod())
//            orderUserApplyDetail.setLoanPeriod(channelCustomerApplyCommand.getLoanPeriod());
//        orderUserApplyDetail.setJdBtQuota(channelCustomerApplyCommand.getJdBtQuota());
//        orderUserApplyDetail.setAntCreditPayQuota(channelCustomerApplyCommand.getAntCreditPayQuota());
//        orderUserApplyDetail.setSex(channelCustomerApplyCommand.getSex());
//        orderUserApplyDetail.setAge(channelCustomerApplyCommand.getAge());
//        return orderUserApplyDetail;
//    }
//}
